#include <stdio.h>
#include <linux/unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <pthread.h>
#include "test_barrier_header.h"


void *thread_function( void *ptr );

int main(int argc, char *argv[])
{
	
	int j;
	if(argc!=3)
	{
		printf(" You need to pass two args N(barrier size) and M(processes)");
		return -1;
	}
	int N=atoi(argv[1]);
	int M=atoi(argv[2]);
	int id =(int)barriercreate(N);
	if(id < 0)
	{
		perror("barriercreate: ");
		printf("Barrier Create error \n");
		return -1;
	}
	printf("Barrier Created\n");
	
	pthread_t threads[M];
	
	for(j=0;j<M;j++)
	{
		pthread_create( &threads[j], NULL, thread_function, (void*) &id);
	}
	for(j=0;j<M;j++)
	{
	pthread_join( threads[j], NULL);
	
	}
	printf("Destroying barrier\n");
	int ret=barrierdestroy(id);
	if(ret<0)
	{
		printf("Error in Destroy\n");
	}

	printf("DESTROYED\n");

	return 0;
}


void *thread_function( void *ptr )
{
     
	 int *idptr = (int *) ptr;
	 
	 printf("Thread number %ld\n", pthread_self());
	 printf("Before Wait\n");
	 int ret=barrierwait(*idptr);
	 if(ret!=0)
	 {
		 printf("Error in Wait\n");

	 }
	 printf("Wait Over- Now Returning to main %ld\n", pthread_self());
	 return;
     
}

